angular.module('orderdetail', []).controller('orderdetailCtrl', [
    '$scope',
    'httpService',
    '$stateParams',
    '$timeout',
    'alertmsg',
    '$state',
    '$localStorage',
    '$rootScope',
    'confirmservice',
    '$interval',
    '$sce',
    function($scope, httpService, $stateParams, $timeout, alertmsg, $state, $localStorage, $rootScope, confirmservice, $interval, $sce) {
        var oldorder;
        $scope.goMap = function(role, id) {
            if (role == 2) {
                $state.go('service-maporders', { id: id });
            }
        };
        // 服务商修改订单
        $scope.changeOrder = function(order) {
            $state.go('mine.changeorder', { id: order.id });
        };

        $scope.statesArrs = angular.copy(statesArrs);
        var newstatesArrs = angular.copy(statesArrs);
        $scope.arrindex = 0;

        var time = new Date().getTime();
        var opts = {
            minDate: new Date(),
            enableTime: true,
            dateFormat: 'Y-m-d H:i',
            mode: 'single',
            locale: 'zh',
            onChange: function(selectedDates, dateStr, instance) {
                var selectTime = new Date(selectedDates[0]).getTime() / 1000;
                if ('changeflatpickr' == instance.element.id) {
                    if ($scope.order.mount_order) {
                        $scope.order.install_date = selectTime;
                    } else {
                        $scope.order.booking_date = selectTime;
                    }
                } else if (instance.element.id == 'flatpickrc') {
                    $scope.order.install_date = selectTime;
                }
            }
        };
        $.getScript('./lib/flatpickr/dist/l10n/zh.js', function() {
            flatpickr("#changeflatpickr", opts);
            opts.minDate = new Date($stateParams.time * 1000);
            $timeout(function() {
                flatpickr("#flatpickrc", opts);
            }, 500)
        });

        function setArrIndex(data) {
            // var staarr = angular.copy(statesArrs);
            // if (data.workflow_state != 'canceled') {
            //     staarr.splice(staarr.length - 1, 1);
            //     $scope.statesArrs = staarr;
            // }
            $scope.setisinstalltime = true;
            if (!data.install_date && data.workflow_state == 'appointed_installation') {
                $scope.setisinstalltime = false;
            }
            if (data.mount_order) {
                $scope.statesArrs.splice(1, 2);
                newstatesArrs.splice(1, 2);
            }
            angular.forEach(newstatesArrs, function(v, k) {
                if (v.state.split(',').indexOf(data.workflow_state) != -1) {
                    $scope.arrindex = k;
                }
            });
        }

        var id = $stateParams.id;
        // 根据id获取订单详情
        // 2 修改 installed ，completed
        $scope.getOrderById = function() {
            httpService.query('web/orders/' + id).then(function(res) {
                if (res.code == 200) {
                    $scope.order = res.order;
                    if (res.order.mount_order) {
                        opts.defaultDate = res.order.install_date * 1000;
                    } else {
                        opts.defaultDate = res.order.booking_date * 1000;
                    }
                    flatpickr("#changeflatpickr", opts);
                    if (res.order.comment) {
                        $scope.comment.raty = res.order.comment.raty;
                        $scope.comment.content = res.order.comment.content;
                    }
                    setArrIndex($scope.order);
                }
            });
        };
        $scope.getOrderById();

        // 编辑订单
        $scope.ismodalorderform1 = false;
        $scope.putOrderDetail = function(bool, order, ismaster, isUpdateMaster) {
            if (!bool) {
                var obj = {
                    id: order.id,
                    name: order.name,
                    tel: order.tel,
                    facilitator_id: order.facilitator_id
                };
                if (order.booking_date) {
                    obj.booking_date = order.booking_date;
                }
                if (order.install_date) {
                    obj.install_date = order.install_date;
                }
                httpService.query('web/orders/' + order.id, obj, 'put').then(function(res) {
                    $('#myModal').modal('hide');
                    if (res.code == 200) {
                        if (ismaster && oldorder && oldorder.facilitator_id != $scope.order.facilitator_id) {
                            window.history.go(-1);
                        }
                        if (isUpdateMaster) {
                            alertmsg('订单成功指派给' + $scope.order.service_info.name + '了！');
                        }
                        $scope.order = res.order;
                        $('#speedimg1').ready(function(e) {
                            loadDefaultPic(e, '#speedimg1', '#previewul1', 9);
                        });
                    } else {
                        alert(res.msg);
                    }
                });
            } else {
                $scope.ismodalorderform1 = true;
            }
        };

        // 取消订单
        $scope.deleteOrder = function(id, index) {
            confirmservice('是否取消？').then(function(bool) {
                if (bool) {
                    httpService.query('web/orders/' + id, '', 'delete').then(function(res) {
                        if (res.code == 200) {
                            $scope.order = res.order;
                            alertmsg('取消订单成功！');
                        } else {
                            alertmsg(res.msg);
                        }
                    });
                }
            });
        };

        // 预约安装时间
        $scope.changeInstallTime = false;
        $scope.changeTime = function() {
            opts.minDate = new Date($stateParams.time * 1000);
            opts.defaultDate = $scope.order.install_date * 1000;
            flatpickr("#flatpickrc", opts);
            $scope.changeInstallTime = true;
        };


        $scope.$watch('order', function(newData, oldData) {
            $scope.isinstalltime = true;
            if (oldorder && !oldorder.install_date) {
                $scope.isinstalltime = false
            }
        })
        $scope.installTime = function() {
            if ($scope.order && $scope.order.install_date) {
                httpService.query('web/orders/' + id + '/installed_form', {
                    install_date: $scope.order.install_date
                }, 'post').then(function(res) {
                    if (res.code == 200) {
                        $scope.changeInstallTime = false;
                        setArrIndex(res.order);
                        $scope.order = res.order;
                        alertmsg('预约安装时间成功');
                    } else {
                        alertmsg(res.msg);
                    }
                })
            } else {
                alertmsg('请选择预约安装时间!');
            }
        };

        function showError(msg) {
            $scope.noperson = msg;
            $timeout(function() {
                $scope.noperson = '';
            }, 1500);
        }

        // 搜索安装师傅
        $scope.getMaster = function(keyword) {
            var first = 1;
            $scope.noperson = '';
            if (keyword && first == 1) {
                ++first;
                httpService.query('web/users/fetch_master', {
                    keyword: keyword,
                    page: 1,
                    limit: limit
                }).then(function(res) {
                    first == 1;
                    if (res.code == 200) {
                        $scope.masters = res.users;
                    } else {
                        alertmsg(res.msg);
                    }
                }, function() {
                    first == 1;
                });
            } else {
                first == 1
                showError('请输入关键字!');
            }
        };

        function waitGetMaster() {
            var timer;
            if (timer) {
                $interval.cancel(time);
            }

            timer = $interval(function() {
                $scope.getMaster($scope.keyword);
                $interval.cancel(timer);
            }, 500);
        }

        $scope.$watch('keyword', function(newData, oldData) {
            if (newData) {
                waitGetMaster();
            }
        });

        // 设定师傅
        $scope.setMaster = function(master) {
            oldorder = angular.copy($scope.order);
            $scope.order.facilitator_id = master.id;
            $scope.order.service_info.name = master.real_name;
            $scope.master = master;
            $scope.masters = null;
            $scope.keyword = '';
            $('.servermodal').modal('hide')
        };

        $scope.updateTimeAndMaster = function(bool, order, self) {
            var obj = {
                id: $scope.order.id,
                facilitator_id: $scope.order.facilitator_id
            };
            if ($scope.order.install_date) {
                $scope.setisinstalltime = true;
                obj.install_date = $scope.order.install_date;
                $scope.putOrderDetail(false, obj, true);
            } else {
                if (!self) {
                    alertmsg('请选择预约安装时间！');
                    return
                }
                $scope.putOrderDetail(false, obj, true, self);
            }
        };

        // 确认安装
        $scope.installed = function() {
            confirmservice('是否确认安装完成？').then(function(bool) {
                if (bool) {
                    httpService.query('web/orders/' + id + '/state_event', {}, 'post').then(function(res) {
                        if (res.code == 200) {
                            setArrIndex(res.order);
                            $scope.order = res.order;
                            alertmsg('安装完成！');
                        } else {
                            alertmsg(res.msg);
                        }
                    });
                }
            });
        };

        // 评分
        $scope.comment = {
            raty: 5,
            content: '服务很好，会推荐给朋友！'
        };
        $scope.arrs = [1, 2, 3, 4, 5];
        $scope.commentOrder = function(comment) {
            httpService.query('web/orders/' + id + '/comments', comment, 'post').then(function(res) {
                if (res.code == 200) {
                    setArrIndex(res.order);
                    $scope.order = res.order;
                    if (res.order.comment) {
                        $scope.comment.raty = res.order.comment.raty;
                        $scope.comment.content = res.order.comment.content;
                    }
                    $scope.getOrderById();
                } else {
                    alertmsg(res.msg);
                }
            });
        };
        // 设置评分
        $scope.setRaty = function(raty, state) {
            if (state != 'completed') {
                $scope.comment.raty = raty;
            }
        };

        $scope.getPersion = function() {
            httpService.query('web/users/' + $localStorage.user.id).then(function(res) {
                if (res.code == 200) {
                    $localStorage.user = $rootScope.user = res.user;
                }
            })
        };

        // 用户支付订单
        $scope.payOrder = function() {
            if (!isMobile) {
                pay_type = 'alipay_pc_direct';
            }
            httpService.query('web/orders/' + id + '/payment', {
                pay_type: pay_type
            }, 'post').then(function(res) {
                $('#payModal').modal('hide');
                if (res.code == 200) {
                    $scope.getPersion();
                    setArrIndex(res.order);
                    $scope.order = res.order;
                    alertmsg('支付成功!');
                } else {
                    alertmsg(res.msg);
                    if (res.code == 301) {
                        $state.go('mine.recharge', { money: $scope.order.total });
                    }
                }
            });
        };

        // 加载默认图片
        var defaultpic = './components/mine/orders/orderdetail/imgs/add.png';

        function loadDefaultPic(e, parent, child, num) {
            $scope.loadDefaultPics = [];
            pics = [];
            var previewul = $(child);
            previewul.off('click', 'li');
            previewul.find('li').remove();
            if (!num) {
                num = 6;
            }
            for (var i = 0; i < num; i++) {
                $scope.loadDefaultPics.push(defaultpic);
                pics.push(false);
                var html = '<li><img id="previewid' + i + '" data-index="' + i + '" src="' + defaultpic + '" /></li>'
                $(child).append(html);
            }
            changePic(e, parent, child, num);
        }

        // 渲染图片
        function rendererPic(child, i, defaultpic) {
            var html = '<li><img id="previewid' + i + '" data-index="' + i + '" src="' + defaultpic + '" /></li>'
            $(function() {
                $(child).append(html);
            });
        }

        // 更改图片
        function changePic(e, parent, child, num) {
            var previewul = $(child);
            previewul.on('click', 'li', function(e, b, c) {
                changeindex = e.target.id.split('previewid')[1];
                speedimgid = parent + changeindex;
                var img = $(child).find('li').eq(changeindex).find('img')[0];
                $(speedimgid).click();
                $(speedimgid).change(function(ec) {
                    onefiles = ec.target.files || ec.dataTransfer.files;
                    var fReader = new FileReader();
                    fReader.readAsDataURL(onefiles[0]);
                    fReader.onloadend = function(event) {
                        pics[changeindex] = true;
                        img.src = event.target.result;
                    }
                });
            });
        }

        // 预览图片
        var pics = [];
        $scope.$watch('order.workflow_state', function(newData, oldData) {
            if (['appointed_measurement', 'measured'].indexOf(newData) != -1) {
                $('#speedimg').ready(function(e) {
                    loadDefaultPic(e, '#speedimg', '#previewul', 6);
                });
            } else if (newData == 'appointed_installation') {
                $('#speedimg1').ready(function(e) {
                    loadDefaultPic(e, '#speedimg1', '#previewul1', 9);
                });
            }
        });

        var firstImgUpload = true;
        $scope.completed = function(type, imgtype, element_id) {
            if (firstImgUpload) {
                firstImgUpload = false;
                var f = new FormData();
                angular.forEach(pics, function(v, k) {
                    if (v) {
                        var file = document.getElementById(element_id + k).files[0];
                        f.append('pictures[][image]', file);
                        f.append('pictures[][image_type]', imgtype);
                    }
                });
                $timeout(function() {
                    httpService.query('web/orders/' + id + '/upload_data', f, 'post', true).then(function(res) {
                        firstImgUpload = true;
                        if (res.code == 200) {
                            $('#speedimg').ready(function(e) {
                                loadDefaultPic(e, '#speedimg', '#previewul', 6);
                            });
                            $scope.order = res.order;
                            setArrIndex(res.order);
                        } else {
                            alertmsg(res.msg);
                        }
                    }, function() {
                        firstImgUpload = true;
                    });
                }, 500);
            } else {
                alertmsg('上传中请稍等！');
            }
        };

        $scope.downloadPdf = function(url) {
            var split_url = url.slice(-3);
            if (['pdf', 'dwg'].indexOf(split_url) != -1) {
                window.open($sce.trustAsUrl(url), '_blank');
            }
        };

        $scope.closeModal = function() {
            $('#myModal').modal('hide');
        };

        // 上传文件信息
        $scope.uploadFile = function() {
            console.log($('#xml-file'))
            console.log($("#xml-file")[0].files[0])
            var file = $("#xml-file")[0].files[0]
            var f = new FormData()
            if (file) {
                f.append('pictures[][image]', file)
                f.append('pictures[][image_type]', 'xml')
                httpService.query('web/orders/' + id + '/upload_data', f, 'post', true).then(function(res) {
                    console.log(res)
                })
            }
        };
    }
]);
